package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.csu.onlineedubackend.entity.ForumComment;
import org.csu.onlineedubackend.entity.ForumPost;
import org.csu.onlineedubackend.entity.ForumNotification;
import org.csu.onlineedubackend.mapper.ForumCommentMapper;
import org.csu.onlineedubackend.mapper.ForumNotificationMapper;
import org.csu.onlineedubackend.mapper.ForumPostMapper;
import org.csu.onlineedubackend.service.ForumCommentService;
import org.csu.onlineedubackend.service.ForumUserStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ForumCommentServiceImpl implements ForumCommentService {
    @Autowired
    private ForumCommentMapper forumCommentMapper;
    
    @Autowired
    private ForumPostMapper forumPostMapper;
    
    @Autowired
    private ForumUserStatsService forumUserStatsService;

    @Autowired
    private ForumNotificationMapper forumNotificationMapper;

    @Override
    public boolean createComment(ForumComment comment) {
        comment.setStatus("active");
        boolean success = forumCommentMapper.insert(comment) > 0;
        
        if (success) {
            // 判斷接收者
            Integer receiverId = null;
            Integer notifType = 2; // 默認評論
            Integer targetType = 1; // 1=帖子
            Integer targetId = comment.getPostId();
            String content = "您的帖子收到了一條評論";

            if (comment.getParentId() != null) {
                // 這是回覆
                ForumComment parent = forumCommentMapper.selectById(comment.getParentId());
                if (parent != null) {
                    receiverId = parent.getUserId();
                    notifType = 4; // 回覆
                    targetType = 1; // 目標是帖子
                    targetId = comment.getPostId(); // 回复所屬帖子ID
                    content = "您的評論收到了一條回覆";
                }
            } else if (comment.getPostId() != null) {
                ForumPost post = forumPostMapper.selectById(comment.getPostId());
                if (post != null) {
                    receiverId = post.getUserId();
                }
            }

            // 避免自己給自己發通知
            if (receiverId != null && !receiverId.equals(comment.getUserId())) {
                ForumNotification notification = new ForumNotification();
                notification.setUserId(receiverId);
                notification.setSenderId(comment.getUserId());
                notification.setType(notifType);
                notification.setTargetType(targetType);
                notification.setTargetId(targetId);
                notification.setContent(content);
                notification.setIsRead(0);
                forumNotificationMapper.insert(notification);
            }
        }
        
        // 更新被評論帖子作者的統計數據
        if (success && comment.getPostId() != null) {
            ForumPost post = forumPostMapper.selectById(comment.getPostId());
            if (post != null) {
                forumUserStatsService.incrementCommentCount(post.getUserId());
            }
        }
        
        return success;
    }

    @Override
    public boolean deleteComment(Integer commentId, Integer userId) {
        ForumComment comment = forumCommentMapper.selectById(commentId);
        if (comment == null || !comment.getUserId().equals(userId)) {
            return false;
        }
        comment.setStatus("deleted");
        boolean success = forumCommentMapper.updateById(comment) > 0;
        
        // 更新被評論帖子作者的統計數據
        if (success && comment.getPostId() != null) {
            ForumPost post = forumPostMapper.selectById(comment.getPostId());
            if (post != null) {
                forumUserStatsService.decrementCommentCount(post.getUserId());
            }
        }
        
        return success;
    }

    @Override
    public IPage<ForumComment> getCommentsByPost(Page<ForumComment> page, Integer postId) {
        LambdaQueryWrapper<ForumComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumComment::getPostId, postId)
               .eq(ForumComment::getStatus, "active")
               .orderByAsc(ForumComment::getCreatedAt);
        return forumCommentMapper.selectPage(page, wrapper);
    }

    @Override
    public List<ForumComment> getRepliesByParent(Integer parentId) {
        LambdaQueryWrapper<ForumComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumComment::getParentId, parentId)
               .eq(ForumComment::getStatus, "active")
               .orderByAsc(ForumComment::getCreatedAt);
        return forumCommentMapper.selectList(wrapper);
    }
    
    @Override
    public int getCommentCountByPost(Integer postId) {
        LambdaQueryWrapper<ForumComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumComment::getPostId, postId)
               .eq(ForumComment::getStatus, "active");
        return forumCommentMapper.selectCount(wrapper).intValue();
    }

    @Override
    public int getUserReceivedCommentCount(Integer userId) {
        // 1. 查詢用戶的所有帖子
        LambdaQueryWrapper<ForumPost> postWrapper = new LambdaQueryWrapper<>();
        postWrapper.eq(ForumPost::getUserId, userId);
        List<ForumPost> userPosts = forumPostMapper.selectList(postWrapper);

        // 2. 統計這些帖子收到的評論數
        int totalComments = 0;
        for (ForumPost post : userPosts) {
            LambdaQueryWrapper<ForumComment> commentWrapper = new LambdaQueryWrapper<>();
            commentWrapper.eq(ForumComment::getPostId, post.getId())
                          .eq(ForumComment::getStatus, "active");
            totalComments += forumCommentMapper.selectCount(commentWrapper).intValue();
        }
        return totalComments;
    }
} 